<?php

// 微信绑定
// PUT member.wxBind

namespace app\api\resource\member;
use think\Db;
use think\Loader;
use think\Session;
use app\common\logic\Login as LoginLogic;

class WxBind
{
    // 方法
    public $_method = ['PUT'];
    // 前置
    public $_pre    = ['wxOauth','sms'];
    // 描述
    public $_description = '微信绑定';
    // 参数
    public $_param  = [
        'model'  => '模式,0-公众号绑定(默认)|1-PC扫码绑定',
        'mobile' => '手机号',
    ];
    // 返回
    public $_return = [
        201 => '绑定成功',
        400 => '该微信号已被注册|手机关联帐号不存在',
        422 => '请求参数不合法',
        500 => '服务器错误',
    ];

    public function run(&$request)
    {
        $model = $request->post('model/d',0);

        $params['unionid'] = Session::get('wechat.unionid');
        $params['openid']  = (0 == $model) ? Session::get('wechat.openid') : '';
        $params['mobile']  = $request->put('mobile/s','','trim');

        $validate = Loader::validate('Member');
        if ( !$validate->scene('wxBind')->check($params) ) {
            $errMsg = $validate->getError();
            return [422,$errMsg];
        }

        $ret = Db::name('member')->where('unionid',$params['unionid'])->field('id')->find();
        if ( !is_null($ret) ) return [400,'该微信号已被注册'];

        $ret = Db::name('member')->where('mobile',$params['mobile'])->field('id')->find();
        if ( is_null($ret) ) return [400,'手机关联帐号不存在'];

        $data['unionid'] = $params['unionid'];
        $data['openid']  = $params['openid'];
        $num = Db::name('member')->where('mobile',$params['mobile'])->update($data);
        if ($num > 0) {
            // 写入Session
            $member = Db::name('member')->where('mobile',$params['mobile'])->field('password',true)->find();

            $member['info'] = Db::name('member_info')->where('member_id',$member['id'])->find();

            // 登录处理
            LoginLogic::run($member);

            // Session::set('member',$member);

            // 删除Session中短信码记录
            Session::delete('sms');

            return [ 201,[] ];
        } else {
            return 500;
        }
    }
}